package com.aiwu

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.aiwu.library.AiwuSimulator
import com.aiwu.library.ui.pop.EditDialog
import com.aiwu.library.util.ActivityMessenger
import com.aiwu.library.util.DialogUtil
import com.aiwu.library.util.OtherSpUtil
import com.aiwu.library.util.ToastUtil
import com.aiwu.utils.PrefsHelper
import com.aiwu.widget.ScreenViewGroup.OnActionListener
import org.citra.citra_emu.R
import org.citra.citra_emu.databinding.ActivityScreenEditBinding

/**
 * 屏幕编辑
 */
class ScreenEditActivity : AppCompatActivity(), OnActionListener {
    companion object {
        private const val EXTRA_ID = "extra_id"
        private const val EXTRA_IS_INSERT = "extra_is_insert"
        const val RESULT_ACTION = "result_action"
        const val RESULT_ID = "result_id"
        const val RESULT_INSERTED = 100
        const val RESULT_EDITED = 101

        /**
         * 外部启动
         *
         * @param activity
         * @param id       配置id
         * @param isInsert 是不是新建
         */
        fun launch(
            activity: Activity,
            id: Int,
            isInsert: Boolean,
            callback: ActivityMessenger.OnActivityResultCallBack
        ) {
            ActivityMessenger.startActivityForResult(
                activity,
                Intent(activity, ScreenEditActivity::class.java)
                    .putExtra(EXTRA_ID, id)
                    .putExtra(EXTRA_IS_INSERT, isInsert),
                callback, null
            )
        }
    }

    private val binding by lazy {
        ActivityScreenEditBinding.inflate(layoutInflater)
    }

    //配置id
    private var mConfigId = 0

    //新建配置
    private var mIsInsert = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        if (AiwuSimulator.isNotchPhone()) {
            window?.let {
                val shouldExpand = OtherSpUtil.getInstance().expandToCutout
                it.setAttributes(window.attributes.apply {
                    layoutInDisplayCutoutMode =
                        if (shouldExpand) WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
                })
            }
        }
        enableFullscreenImmersive()
        mConfigId = intent.getIntExtra(EXTRA_ID, -1)
        mIsInsert = intent.getBooleanExtra(EXTRA_IS_INSERT, true)
        if (mConfigId == -1) {
            errorFinish()
            return
        }
        binding.screenViewGroup.setOnActionListener(this)
        initData()
    }

    private fun initData() {
        if (mIsInsert) { //新建
            binding.screenViewGroup.post { binding.screenViewGroup.addDefaultScreenView() }
        } else { //编辑
            val screenConfig = PrefsHelper.instance.getScreenConfig(mConfigId)
            if (screenConfig != null) {
                binding.screenViewGroup.post {
                    binding.screenViewGroup.addExistingScreenView(
                        screenConfig.topLeft,
                        screenConfig.topTop,
                        screenConfig.topRight,
                        screenConfig.topBottom,
                        screenConfig.bottomLeft,
                        screenConfig.bottomTop,
                        screenConfig.bottomRight,
                        screenConfig.bottomBottom
                    )
                }
            } else {
                errorFinish()
            }
        }
    }

    private fun errorFinish() {
        ToastUtil.toast("获取参数出错!")
        setResult(RESULT_CANCELED)
        finish()
    }

    private fun successFinish() {
        setResult(
            RESULT_OK,
            Intent().putExtra(RESULT_ACTION, if (mIsInsert) RESULT_INSERTED else RESULT_EDITED)
                .putExtra(RESULT_ID, mConfigId)
        )
        finish()
    }

    override fun onBackPressed() {
        showSaveConfigTip()
    }

    override fun showSaveConfigTip() {
        DialogUtil.showTip(this, R.string.emu_lib_save_config_tip, {
            if (mIsInsert) {
                showInputNameTip()
            } else {
                saveConfigValue()
            }
        }) {
            setResult(RESULT_CANCELED)
            finish()
        }
    }

    override fun resetScreenView() {
        if (mIsInsert) {
            binding.screenViewGroup.resetDefaultScreenView()
        } else {
            PrefsHelper.instance.getScreenConfig(mConfigId)?.let {
                binding.screenViewGroup.resetExistingScreenView(
                    it.topLeft,
                    it.topTop,
                    it.topRight,
                    it.topBottom,
                    it.bottomLeft,
                    it.bottomTop,
                    it.bottomRight,
                    it.bottomBottom
                )
            }
        }
    }

    /**
     * 命名弹窗
     */
    private fun showInputNameTip() {
        object : EditDialog(this) {
            override fun initView() {
                val tvTitle = findViewById<TextView>(R.id.tv_title)
                tvTitle.text = "输入配置名称"
                val et = findViewById<EditText>(R.id.et)
                et.setHint(R.string.emu_lib_input_config_name)
                val btnCancel = findViewById<TextView>(R.id.btn_cancel)
                val btnConfirm = findViewById<TextView>(R.id.btn_confirm)
                btnCancel.setOnClickListener { dismiss() }
                btnConfirm.setOnClickListener {
                    val newName = et.getText().toString()
                    if (TextUtils.isEmpty(newName)) {
                        ToastUtil.toast(R.string.emu_lib_config_name_empty)
                        return@setOnClickListener
                    }
                    dismiss()
                    saveNewConfig(newName)
                }
            }
        }.show()
    }

    /**
     * 保存新配置
     */
    private fun saveNewConfig(name: String) {
        if (binding.screenViewGroup.getResultLocation().size != 8) {
            return
        }
        val result = binding.screenViewGroup.getResultLocation()
        PrefsHelper.instance.saveNewScreenConfig(
            mConfigId,
            name,
            result[0],
            result[1],
            result[2],
            result[3],
            result[4],
            result[5],
            result[6],
            result[7]
        )
        successFinish()
    }

    /**
     * 保存配置
     */
    private fun saveConfigValue() {
        if (binding.screenViewGroup.getResultLocation().size != 8) {
            return
        }
        val result = binding.screenViewGroup.getResultLocation()
        PrefsHelper.instance.editScreenConfigValue(
            mConfigId,
            result[0],
            result[1],
            result[2],
            result[3],
            result[4],
            result[5],
            result[6],
            result[7]
        )
        successFinish()
    }

    private fun enableFullscreenImmersive() {
        window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_FULLSCREEN or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    }
}
